package com.czn.shopdemo.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czn.shopdemo.mapper.UserMapper;
import com.czn.shopdemo.model.User;
import com.czn.shopdemo.service.UserService;
import com.czn.shopdemo.utils.JwtUtil;
import com.czn.shopdemo.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);


    /*
     * 在请求处理之前进行调用(Controller方法调用之前)
     * 若返回true请求将会继续执行后面的操作
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果不是映射到方法不拦截 直接通过
//        if (!(handler instanceof HandlerMethod)) {
//            return true;
//        }
        String requestURI = request.getRequestURI();
        if (!Utils.isEmptyStr(requestURI) && requestURI.contains("swagger")) {
            return true;
        }
        if(!Utils.isEmptyStr(requestURI) && requestURI.contains("payment/result")){
            return true;
        }
        //验证token
        Long userId = JwtUtil.getUserId(token);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", String.valueOf(userId));
        User user = userMapper.selectOne(queryWrapper);
        if (null == token || "".equals(token) || null == user) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try (PrintWriter writer = response.getWriter()) {
                writer.print("需要先进行登陆才可以访问！");
            } catch (Exception e) {
                log.error("", e);
                log.error("login token error is {}", e.getMessage());
            }
            return false;
        }
        return true;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
